module.exports = app => {

  const express = require('express')
  const router = express.Router({
    mergeParams: true
  })

  // 提交数据
  router.post('/', async (req, res) => {
    const model = await req.Model.create(req.body)
    res.send(model)
  })

  // 获取数据
  router.get('/', async (req, res) => {
    const queryOptions = {}
    const resource = req.params.resource
    if(resource == 'categories') {
      queryOptions.populate = 'parent'
    }
    if(resource == 'hero') {
      const items = await req.Model.find().populate([
        { path: 'position' },
        { path: 'equipment1', select: { name: 1, icon: 1 } },
        { path: 'equipment2', select: { name: 1, icon: 1 } },
        { path: 'partners.hero', select: { name: 1, avatar: 1 } }
      ]).limit(50)
      res.send(items)
      return ;
    }
    const items = await req.Model.find().setOptions(queryOptions).limit(50)
    res.send(items)
  })

  // 查询数据
  router.get('/id', async (req, res) => {
    const model = await req.Model.findById(req.query.id)
    res.send(model)
  })

  // 更新数据
  router.post('/update', async (req, res) => {
    const model = await req.Model.updateOne({"_id": req.body.id}, {"$set": req.body})
    res.send(model)
  })

  // 删除数据
  router.get('/delete', async (req, res) => {
    await req.Model.findByIdAndRemove(req.query.id)
    res.send({success: true})
  })

  app.use('/admin/api/rest/:resource', (req, res, next) => {
    let modelName = req.params.resource
    let str = modelName[0].toUpperCase()
    modelName = modelName.replace(modelName[0], str)

    req.Model = require(`../../models/${modelName}`)
    next()
  }, router)

  // 上传图片
  const multer = require('multer')
  const upload = multer({ dest: __dirname + '/../../uploads' })
  app.post('/admin/api/upload', upload.single('file'), async (req, res) => {
    res.send(req.file)
  })

  // 登录接口
  app.post('/admin/api/login', async (req, res) => {
    const Account = require('../../models/Account')
    const { username, password } = req.body
    // 1. 根据用户名查找用户是否存在
    const user = await Account.findOne({ username }).select('+password')
    if(!user) {
      return res.status(422).send({
        type: 'warning',
        message: '账号不存在'
      })
    }
    // 2. 验证密码是否正确
    // const bool = require('bcrypt').compareSync(password, user.password)
    if(password !== user.password) {
      return res.status(422).send({
        type: 'error',
        message: '密码错误'
      })
    }
    const jwt = require('jsonwebtoken')
    const token = jwt.sign({ id: user._id }, app.get('secret'))
    res.send({ token })
  })

}
